package org.apache.flink.runtime.resourceconsumer;

import java.util.UUID;
import java.util.concurrent.CompletableFuture;

import javax.annotation.concurrent.GuardedBy;

import org.apache.flink.api.common.ConsumerID;
import org.apache.flink.runtime.allocation.ResourceAllocation;
import org.apache.flink.runtime.client.ConsumerInitializationException;
import org.apache.flink.runtime.consumermanager.OnCompletionActions;
import org.apache.flink.runtime.resourceconsumer.factories.ResourceConsumerServiceFactory;
import org.apache.flink.runtime.resourceconsumer.runner.ResourceConsumerRunnerResult;
import org.apache.flink.util.ERException;
import org.apache.flink.util.concurrent.FutureUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @类名: DefaultResourceConsumerServiceProcess
 * @说明: ResourceConsumerServiceProcess实现
 *
 * @author   leehom
 * @Date	 2023年11月1日 下午2:44:24
 * 修改记录：
 *
 * @see 	 
 */
/**
 * Default {@link ResourceConsumerServiceProcess} which is responsible for creating and running a {@link
 * ResourceConsumerService}. The process is responsible for receiving the signals from the {@link
 * ResourceConsumerService} and to create the respective {@link ResourceConsumerRunnerResult} from it.
 * 默认的ResourceConsumerServiceProcess实现，负责构建和运行ResourceConsumerService。
 * process负责接收ResourceConsumerService的信号，并据此创建相应的ResourceConsumerRunnerResult
 *
 * <p>The {@link ResourceConsumerService} can be created asynchronously and the creation can also fail.
 * That is why the process needs to observe the creation operation and complete the {@link
 * #resultFuture} with an initialization failure.
 *
 * <p>The {@link #resultFuture} can be completed with the following values:
 *
 * <ul>
 *   <li>{@link ResourceConsumerRunnerResult} to signal an initialization failure of the {@link
 *       ResourceConsumerService} or the completion of a job
 *   <li>{@link ConsumerNotFinishedException} to signal that the job has not been completed by the {@link
 *       ResourceConsumerService}
 *   <li>{@link Exception} to signal an unexpected failure
 * </ul>
 */
public class DefaultResourceConsumerServiceProcess
        			implements ResourceConsumerServiceProcess, OnCompletionActions {

    private static final Logger LOG = LoggerFactory.getLogger(DefaultResourceConsumerServiceProcess.class);

    /** */
    private final Object lock = new Object();
    /** */
    private final ConsumerID consumerId;
    /** */
    private final UUID leaderSessionId;
    /** 构建资源消费服务异步结果*/
    private final CompletableFuture<ResourceConsumerService> resourceConsumerServiceFuture;
    /** 终止服务结果*/
    private final CompletableFuture<Void> terminationFuture = new CompletableFuture<>();
    /** */
    private final CompletableFuture<ResourceConsumerRunnerResult> resultFuture =
            			new CompletableFuture<>();
    /** */
    private final CompletableFuture<ResourceConsumerGateway> resourceConsumerGatewayFuture =
            			new CompletableFuture<>();
    /** */
    private final CompletableFuture<String> leaderAddressFuture = new CompletableFuture<>();

    @GuardedBy("lock")
    private boolean isRunning = true;

    public DefaultResourceConsumerServiceProcess(
            ConsumerID consumerId,
            UUID leaderSessionId,
            ResourceConsumerServiceFactory resourceConsumerServiceFactory) {
        this.consumerId = consumerId;
        this.leaderSessionId = leaderSessionId;
        // 构建ResourceConsumerService, 即
        this.resourceConsumerServiceFuture =
                resourceConsumerServiceFactory.createResourceConsumerService(leaderSessionId, this);
        // 构建ResourceConsumerService异步处理
        resourceConsumerServiceFuture.whenComplete(
                (resourceConsumerService, throwable) -> {
                    if (throwable != null) {
                        final ConsumerInitializationException consumerInitializationException =
                                new ConsumerInitializationException(
                                        consumerId, "Could not start the ResourceConsumer.", throwable);
                        LOG.debug(
                                "Initialization of the ResourceConsumerService for consumer {} under leader id {} failed.",
                                consumerId,
                                leaderSessionId,
                                consumerInitializationException);
                        //
                        resultFuture.complete(
                                ResourceConsumerRunnerResult.forInitializationFailure(
                                		null,
                                        consumerInitializationException));
                    } else {
                        registerResourceConsumerServiceFutures(resourceConsumerService);
                    }
                });
    }

    private void registerResourceConsumerServiceFutures(ResourceConsumerService resourceConsumerService) {
        LOG.debug(
                "Successfully created the ResourceConsumerService for consumer {} under leader id {}.",
                consumerId,
                leaderSessionId);
        resourceConsumerGatewayFuture.complete(resourceConsumerService.getGateway());
        leaderAddressFuture.complete(resourceConsumerService.getAddress());

        resourceConsumerService
                .getTerminationFuture()
                .whenComplete(
                        (unused, throwable) -> {
                            synchronized (lock) {
                                if (isRunning) {
                                    LOG.warn(
                                            "Unexpected termination of the ResourceConsumerService for consumer {} under leader id {}.",
                                            consumerId,
                                            leaderSessionId);
                                    resourceConsumerFailed(
                                            new ERException(
                                                    "Unexpected termination of the JobMasterService.",
                                                    throwable));
                                }
                            }
                        });
    }

    @Override
    public CompletableFuture<Void> closeAsync() {
        synchronized (lock) {
            if (isRunning) {
                isRunning = false;

                LOG.debug(
                        "Terminating the JobMasterService process for job {} under leader id {}.",
                        consumerId,
                        leaderSessionId);

                resultFuture.completeExceptionally(new ConsumeNotFinishedException(consumerId));
                resourceConsumerGatewayFuture.completeExceptionally(
                        new ERException("Process has been closed."));
                //
                resourceConsumerServiceFuture.whenComplete(
                        (jobMasterService, throwable) -> {
                            if (throwable != null) {
                                // JobMasterService creation has failed. Nothing to stop then :-)
                                terminationFuture.complete(null);
                            } else {
                                FutureUtils.forward(
                                        jobMasterService.closeAsync(), terminationFuture);
                            }
                        });

                terminationFuture.whenComplete(
                        (unused, throwable) ->
                                LOG.debug(
                                        "JobMasterService process for job {} under leader id {} has been terminated.",
                                        consumerId,
                                        leaderSessionId));
            }
        }
        return terminationFuture;
    }

    @Override
    public UUID getLeaderSessionId() {
        return leaderSessionId;
    }

    @Override
    public boolean isInitializedAndRunning() {
        synchronized (lock) {
            return resourceConsumerServiceFuture.isDone()
                    && !resourceConsumerServiceFuture.isCompletedExceptionally()
                    && isRunning;
        }
    }

    @Override
    public CompletableFuture<ResourceConsumerGateway> getResourceConsumerGatewayFuture() {
        return resourceConsumerGatewayFuture;
    }

    @Override
    public CompletableFuture<ResourceConsumerRunnerResult> getResultFuture() {
        return resultFuture;
    }

    @Override
    public CompletableFuture<String> getLeaderAddressFuture() {
        return leaderAddressFuture;
    }

    @Override
    public void consumeReachedGloballyTerminalState(ResourceAllocation allocation) {
        resultFuture.complete(ResourceConsumerRunnerResult.forSuccess(allocation));
    }

    @Override
    public void resourceConsumerFailed(Throwable cause) {
        LOG.debug("Job {} under leader id {} failed.", consumerId, leaderSessionId);
        resultFuture.completeExceptionally(cause);
    }
}
